package com.fjec.market.schedule.handler;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fjec.common.Const;
import com.fjec.market.entity.InfoSpu;
import com.fjec.market.service.IBizRatingService;
import com.fjec.market.service.IInfoSpuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
public class SpuStarHandler {

    @Resource
    private IBizRatingService ratingService;

    @Resource
    private IInfoSpuService spuService;

    public int handle() {
        AtomicInteger count = new AtomicInteger(Const.NUMBER_ZERO);
        // 获取所有评分列表
        List<Map<String, Object>> mapList = ratingService.getSpuStarForSchedule();
        // 更新商品评分
        mapList.forEach(map -> {
            try {
                Long spuId = MapUtils.getLong(map, "SpuId");
                Integer spuStar = MapUtils.getInteger(map, "SpuStar");
                UpdateWrapper<InfoSpu> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("Id", spuId);
                updateWrapper.ne("SpuStar", spuStar);
                InfoSpu entity = new InfoSpu();
                entity.setSpuStar(spuStar);
                boolean result = spuService.update(entity, updateWrapper);
                if (result) {
                    count.getAndIncrement();
                }
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            }
        });
        // 返回处理数量
        return count.intValue();
    }
}
